package com.example.steam520.service;

import com.example.steam520.dao.UserDao;
import com.example.steam520.entity.User;  // 保留自定义User类
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User.UserBuilder;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 校验用户名合法性
        if (username == null || username.trim().isEmpty()) {
            throw new UsernameNotFoundException("用户名不能为空");
        }

        // 2. 根据用户名查询用户（使用trim处理避免空格问题）
        User user = userDao.getUserByUsername(username.trim());
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在：" + username);
        }

        // 3. 根据用户ID查询权限
        List<String> privileges = userDao.getUserPrivilegesByUserId(user.getId());
        if (privileges == null) {
            privileges = List.of();
        }

        // 4. 构建UserDetails返回（使用Spring Security的User类）
        List<SimpleGrantedAuthority> authorities = privileges.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());

        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(authorities)
                .build();
    }
}
